# -*- coding: utf-8 -*-

import os
import yaml
import logging as log
import pandas as pd

from queue import Queue
from typing import List
from com.maycur.gateway.common.base_entity import OpenApiOrgInfo, MaycurWebUser


class AccountManager:
    yaml_path = '../conf/accounts.yml'
    open_api_org_queue: Queue
    web_user_queue: Queue

    def __init__(self):
        self.open_api_org_queue = Queue()
        self.web_user_queue = Queue()

    def _load_account_file(self, load_function):
        with open(os.path.join(os.path.dirname(__file__), self.yaml_path), 'r') as f:
            the_config = yaml.safe_load(f)
            real_path = the_config['locust']['account']['accountFile']

            try:
                load_function(real_path)
            except FileNotFoundError:
                log.error(f'file {real_path} not exists, please check again')

    def _do_load_open_api_orgs(self, real_path: str):
        df = pd.read_excel(real_path)
        for i in df.index.values:
            open_api_org = OpenApiOrgInfo()
            open_api_org.org_name = df.iloc[i, 0]
            open_api_org.app_code = df.iloc[i, 1]
            open_api_org.app_secret = df.iloc[i, 2]
            self.open_api_org_queue.put(open_api_org)

    def file_load_open_api_orgs(self):
        self._load_account_file(self._do_load_open_api_orgs)

    def file_load_web_users(self):
        with open(os.path.join(os.path.dirname(__file__), self.yaml_path), 'r') as f:
            the_config = yaml.safe_load(f)
            real_path = the_config['locust']['account']['accountFile']

            try:
                df = pd.read_excel(real_path)
                for i in df.index.values:
                    web_user = MaycurWebUser()
                    web_user.user_name = df.iloc[i, 0]
                    web_user.phone_number = df.iloc[i, 1]
                    web_user.password = df.iloc[i, 2]
                    web_user.default_ent_code = df.iloc[i, 3]
                    self.web_user_queue.put(web_user)
            except FileNotFoundError:
                log.error(f'file {real_path} not exists, please check again')
